package com.dylan.equipment.utils;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;



/**
 * @author mars
 */
public class StringUtil {
	public static final String DOT_DOT_DOT = "...";
	public static final char Comma = ',';
	public static final String EMPTY = "";
	public static final String BLANK = " ";
	public static final String SLASH = "/";
	public static final String AT = "@";
	public static final String SPLIT = ":";
	public static final String ISO_8859_1 = "iso-8859-1";
	public static final String GBK = "gbk";
	public static final String GB2312 = "gb2312";
	public static final String UTF8 = "utf8";
	private static final String STAR = "*";

	static String[] normalDays = new String[] {//
	//
			"前天",//
			"昨天",//
			"今天",//
			"明天",//
			"后天"//
	};

	// /**
	// * 字母+数字+中文+下划线
	// */
	// public static final String PATTERN_WORD_NUMERIC_CHINESE =
	// "^[a-zA-Z0-9_\u4e00-\u9fa5]*$";
	// /**
	// * 只能是字母和数字
	// */
	// public static final String PATTERN_WORD_NUMERIC = "^[a-zA-Z0-9]*$";
	// /**
	// * 只能是字母
	// */
	// public static final String PATTERN_WORD = "^[a-zA-Z]*$";
	// /**
	// * 只能是数字
	// */
	// public static final String PATTERN_NUMERIC = "^[0-9]*$";
	// /**
	// * 验证email格式
	// */
	// public static final String PATTERN_EMAIL =
	// "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";

	/**
	 * 
	 * {root}/{type}/{server}/{dir}/{filename}.ext<br/>
	 * http://{type}.week08.com/{server}/{dir}/{filename}.ext
	 * 
	 * e.g. \/data\/nfs\/photo\/ys000\/pt000\/xxx.jpg <br/>
	 * http://photo.week08.com/ys000/pt000/xxx.jpg
	 * 
	 * 如果 path 是 http://开头的地址 则直接返回path
	 */
	public static final String convertFileStoragePath(String path, String type) {
		if (path != null && type != null) {
			try {
				if (path.startsWith("http://")) {
					return path;
				}
				path = path.substring(path.indexOf(type) + type.length())
						.replace('\\', '/');
				path = "http://" + type + ".week08.com" + path;
			} catch (Exception e) {
				return path;
			}
		}
		return path;
	}

	/**
	 * 转换时间成差值的方式<br>
	 * 
	 * 例如时间是：2008-08-08 11:15:00<br>
	 * 当前时间是：2008-08-08 11:16:00<br>
	 * 得出的结果是：1分钟之前
	 * 
	 * 例如时间是：2008-08-08 11:15:00<br>
	 * 当前时间是：2008-08-09 11:16:00<br>
	 * 得出的结果是：1天之前
	 * 
	 * 例如时间是：2008-08-08 11:15:00<br>
	 * 当前时间是：2008-08-08 21:16:00<br>
	 * 得出的结果是：10小时之前
	 */
	public static String diffNowTime(Date date) {
		if (date == null)
			return "";
		long now = new Date().getTime();
		long test = date.getTime();
		long span = now - test;
		if (span < 0) {
			return "In the Future";
		}
		for (int i = 0; i < spans.length; i++) {
			if (span >= spans[i]) {
				return (span / spans[i]) + units[i];
			}
		}
		return units[units.length - 1];
	}

	private static long[] spans = { 86400000,// 一天的毫秒
			3600000,// 一小时的毫秒
			60000 // 一分钟的毫秒
	};

	private static String[] units = { "天之前", "小时之前", "分钟之前", "刚刚"};

	/**
	 * 转换时间成生日差值的方式<br>
	 * 
	 * 例如生日时间是：2008-08-08<br>
	 * 当前时间是：2008-08-08<br>
	 * 得出的结果是：今天
	 * 
	 * 例如时间是：2008-08-08<br>
	 * 当前时间是：2008-08-09<br>
	 * 得出的结果是：昨天
	 * 
	 * 例如时间是：2008-08-08<br>
	 * 当前时间是：2008-08-10<br>
	 * 得出的结果是：前天
	 * 
	 * 例如时间是：2008-08-08<br>
	 * 当前时间是：2008-08-07<br>
	 * 得出的结果是：明天
	 * 
	 * 例如时间是：2008-08-08<br>
	 * 当前时间是：2008-08-06<br>
	 * 得出的结果是：后天
	 * 
	 * 例如时间是：2008-08-08<br>
	 * 当前时间是：2008-08-05<br>
	 * 得出的结果是：8月5日
	 */
	public static String diffBirthTime(Date date) {
		if (date == null)
			return "";
		Calendar today = Calendar.getInstance();
		today.set(Calendar.HOUR, 0);
		today.set(Calendar.MINUTE, 0);
		today.set(Calendar.SECOND, 0);

		Calendar test = Calendar.getInstance();
		test.setTime(date);
		test.set(Calendar.HOUR, 0);
		test.set(Calendar.MINUTE, 0);
		test.set(Calendar.SECOND, 0);

		long compare = (test.getTimeInMillis() - today.getTimeInMillis()) / 1000;

		int index = (int) compare / 86400;
		index += 2;
		if (index >= 0 && index < normalDays.length) {
			return normalDays[index];
		}

		SimpleDateFormat abnormalDayFmt = new SimpleDateFormat("yyyy-MM-dd");
		return abnormalDayFmt.format(date);
	}

	/**
	 * len这个长度是按照一个半角的英文或者数字的长度计算的<br>
	 * 如果是中文（日文、韩文、越南）或者全角的英文或者数字<br>
	 * 则请在长度的基础上×2
	 */
	public static String trimDesc(String desc, int len) {
		if (desc == null) {
			return EMPTY;
		}
		int length = desc.length();
		char[] chars = desc.toCharArray();
		int pixCount = 0;
		int index;
		for (index = 0; index < length; index++) {
			char c = chars[index];
			if ((Character.isDigit(c) && !isHalfChar(c))
					|| (isEChar(c) && !isHalfChar(c)))
				pixCount++;
			else
				pixCount += 2;
			if (pixCount >= len) {
				break;
			}
		}
		if (index < length - 1) {
			desc = desc.substring(0, index + 1);
			return desc + DOT_DOT_DOT;
		}
		return desc;
	}

	/**
	 * ascii中的33到126的字符<br>
	 * 包括了a-zA-Z,./?[]{}\|":<>~!@#$%^&*()_+=等等
	 */
	public static boolean isEChar(char c) {
		return c >= 33 && c <= 126;
	}

	public static boolean isHalfChar(char c) {
		return !(('\uFF61' <= c) && (c <= '\uFF9F'))
				&& !(('\u0020' <= c) && (c <= '\u007E'));
	}

	/**
	 * 清除字符串两端的空格，如果参数为null，则返回空字符串
	 * 
	 * @param s
	 * @return
	 */
	public static String trim(String s) {
		if (s == null) {
			return "";
		}
		return s.trim();
	}

	/**
	 * 字符串是否为null或空
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isEmpty(String s) {
		if (s == null)
			return true;
		return trim(s).length() == 0;
	}
	/**
	 * 判断是否不是空
	 * @param str
	 * @return
	 */
	public static boolean isNotEmpty(String str){
		if((str!=null)&&!"".equals(str.trim())){
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 截取字符串最左边的len 个字节
	 * 
	 * @param str
	 * @param len
	 * @return
	 */
	public static String leftB(String desc, int len) {
		if (desc == null) {
			return EMPTY;
		}
		int length = desc.length();
		char[] chars = desc.toCharArray();
		int pixCount = 0;
		int index;
		for (index = 0; index < length; index++) {
			char c = chars[index];
			if ((Character.isDigit(c) && !isHalfChar(c))
					|| (isEChar(c) && !isHalfChar(c)))
				pixCount++;
			else
				pixCount += 2;
			if (pixCount >= len) {
				break;
			}
		}
		if (index < length - 1) {
			desc = desc.substring(0, index + 1);
			return desc + DOT_DOT_DOT;
		}
		return desc;
	}

	/**
	 * 字节长度
	 * 
	 * @param str
	 * @return
	 */
	public static int lenB(String str) {
		str = trim(str);
		return str.getBytes().length;
	}

	/**
	 * 过滤html代码
	 * 
	 * @param s
	 * @return
	 */
	public static String filterHtml(String s) {
		s = trim(s);
		if (s.length() == 0)
			return "";
		String s1 = s;
		s1 = s1.replaceAll("<[^>]*>", "");
		s1 = s1.replaceAll("&{1}[^(&|;)]{2,5};", "");
		s1 = s1.replaceAll("<", "〈");
		s1 = s1.replaceAll(">", "〉");
		return s1;
	}

	/**
	 * 转换html代码，把<和>替换成html表达式
	 * 
	 * @param s
	 * @return
	 */
	public static String escapeHtml(String s) {
		s = trim(s);
		if(s.length() == 0)
			return "";
		s = s.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
		return s;
	}

	// /**
	// * 是否是数字
	// *
	// * @param o
	// * @return
	// */
	// public static boolean isNumeric(Object o) {
	// String s = (String) o;
	// Pattern pattern = Pattern.compile(PATTERN_NUMERIC);
	// Matcher match = pattern.matcher(s);
	// return match.matches();
	// }

	// /**
	// * 是不是格式正确的数据 <BR />
	// * 调用方式，如验证邮箱格式：StringUtil.isRightData("xxxxxx",StringUtil.PATTERN_EMAIL);
	// *
	// * @param o
	// * 要验证的数据
	// * @param pattern
	// * 格式，直接使用内部的常量
	// * @return
	// * @deprecated 请使用ValidatorUtil中的matches方法
	// */
	// public static boolean isRightData(Object data, String pattern) {
	// if (data == null)
	// return false;
	// String s = (String) data;
	// Pattern p = Pattern.compile(pattern);
	// Matcher match = p.matcher(s);
	// return match.matches();
	// }

	

	/**
	 * 修复具有jsessionid的URL，去除jsessionid
	 * 
	 * @param url
	 * @return
	 */
	public static String fixUrlJsession(String url) {
		if (url == null)
			return EMPTY;
		int indexOfJsessionid = url.indexOf(";jsessionid");
		if (indexOfJsessionid > 0) {
			url = url.substring(0, indexOfJsessionid);
		}
		return url;
	}

	/**
	 * 掩盖一定的文字
	 */
	public static String blockString(String value, int start, int end,
			String replace) {
		if (value == null || value.length() <= 0 || start >= end
				|| value.length() <= start)
			return value;
		replace = replace == null || EMPTY.equals(replace) ? STAR : replace;
		end = value.length() < end ? value.length() : end;
		StringBuilder sb = new StringBuilder();
		if (start != 0) {
			sb.append(value.substring(0, start));
		}
		for (int i = 0; i < end; i++)
			sb.append(replace);
		sb.append(value.substring(end));
		return sb.toString();
	}

	/**
	 * 掩盖email。替换@之前的内容start-end的内容
	 * 
	 * @param email
	 * @param end
	 * @param start
	 * @param replace
	 * @return
	 */
	public static String blockEmail(String email, int start, int end,
			String replace) {
		String value = email.substring(0, email.indexOf(AT));
		value = blockString(value, start, end, replace);
		return value += email.substring(email.indexOf(AT));
	}
	/*
	public static String repairHtml(String html) {
		DOMFragmentParser parser = new DOMFragmentParser();
		HTMLDocument document = new HTMLDocumentImpl();

		DocumentFragment fragment = document.createDocumentFragment();
		try {
			StringReader reader=new StringReader(html);
			parser.parse(new InputSource(reader), fragment);
			reader.close();
			StringBuffer sb = new StringBuffer();
			String sr = repairHtml(fragment.getLastChild(), sb);
			Pattern p = Pattern.compile("<body([^>]*)>(.*)</body>",
					Pattern.CASE_INSENSITIVE);
			Matcher m = p.matcher(sr);
			if (m.find()) {
				return (m.group(2));
			}
		} catch (Exception e) {
			return html;
		}
		return html;
	}
	
	private static String repairHtml(org.w3c.dom.Node node, StringBuffer sb) {
		if (node == null) {
			return sb.toString();
		}
		int type = node.getNodeType();
		switch (type) {
		case org.w3c.dom.Node.DOCUMENT_NODE:
			repairHtml(((Document) node).getDocumentElement(), sb);
			break;
		case org.w3c.dom.Node.ELEMENT_NODE:
			sb.append('<');

			sb.append(node.getNodeName());
			NamedNodeMap attrs = node.getAttributes();

			for (int i = 0; i < attrs.getLength(); i++) {
				sb.append(' ');
				sb.append(attrs.item(i).getNodeName());
				sb.append("=\"");

				sb.append(attrs.item(i).getNodeValue());
				sb.append('"');
			}
			sb.append('>');
			// sb.appendln(); // HACK
			org.w3c.dom.NodeList children = node.getChildNodes();
			if (children != null) {
				int len = children.getLength();
				for (int i = 0; i < len; i++) {
					repairHtml(children.item(i), sb);
				}
			}
			break;

		case org.w3c.dom.Node.TEXT_NODE:
			sb.append(node.getNodeValue());
			break;

		}
		if (type == org.w3c.dom.Node.ELEMENT_NODE) {
			sb.append("</");
			sb.append(node.getNodeName());
			sb.append('>');
		}
		return sb.toString();
	}
	*/
	
    /**
     * 加密字符串
     * @param csinput 被加密的字符串
     * @return  返回通过MD5加密后的字符串, 只截取16个字符
     */
	public static String MD5(String csinput,boolean isshort)
    {
        byte[] b, b2 ;
        StringBuffer buf ;
        String csreturn = null ;

        try
        {
            b = csinput.getBytes("iso-8859-1") ;
            MessageDigest md = MessageDigest.getInstance("MD5") ;
            md.update(b) ;
            b2 = md.digest() ;

            buf = new StringBuffer(b2.length * 2) ;
            for (int nLoopindex = 0 ; nLoopindex < b2.length ; nLoopindex++)
            {
                if ( ( (int) b2[nLoopindex] & 0xff) < 0x10)
                {
                    buf.append("0") ;
                }
                buf.append(Long.toString( (int) b2[nLoopindex] & 0xff, 16)) ;
            }
            csreturn = new String(buf);
            if (isshort){
            	csreturn=csreturn.substring(8,24);
            }
        }
        catch (Exception e)
        {
            //e.printStackTrace() ;
            csreturn = "" ;
        }

        return csreturn ;
    }
    
    public static String MD5(String csinput){
    	return MD5(csinput,false);
    }
    
	public static String getUrlHtml(String url){
		int c;
		if (!url.toLowerCase().startsWith("http://")){
			url="http://"+url;
		}
		StringBuffer sb=new StringBuffer();
		try{
			URL Url=new URL(url);
			URLConnection u=Url.openConnection();
			int len=u.getContentLength();
			InputStream in=u.getInputStream();
			int i=len;
			
			while ((c=in.read())!=-1 && --i>0){
					sb.append((char)c);
			}
			in.close();
		}catch(Exception e){
			return e.getMessage();
		}
		String sBody=sb.toString();
		return sBody.trim();
	}
	
	public static String exChs(String s){
		if (isEmpty(s)){
			return "";
		}
		try {
			System.out.print(" 编码前:"+s+"\t");
			s=new String(s.getBytes("iso-8859-1"),"utf-8");
			System.out.println("exChs:"+s);
		} catch (UnsupportedEncodingException e) {
			System.out.println(e);
			e.printStackTrace();
			return "";
		}
		return s;
	}
	
	public static String empty(String s){
		if (s==null){
			return "";
		}
		return s;
	}
	
	public static String empty(Object s){
		if (s==null){
			return "";
		}
		return s.toString();
	}
	
	/**
	 * 转换数据类型为整型 ，转换不成功返回-1
	 * @param num
	 * @return
	 */
	public static int parseInt(String num) {
		if (isEmpty(num)) {
			return -1;
		}
		try {
			return Integer.parseInt(num);
		} catch(Exception e) {
			return -1;
		}
	}
	
	public static long parseLong(String num) {
		if (isEmpty(num)) {
			return -1;
		}
		try {
			return Long.parseLong(num);
		} catch(Exception e) {
			return -1;
		}
	}
	
	public static String toSql(String key) {
		if (isEmpty(key)) {
			return "";
		}
		return key.replace("'", "");
	}
	/**
	 * 数组转换为字符串，以逗号隔开
	 * @param arr
	 * @return
	 */
	public static String arrayToString(String[] arr) {
		return arrayToString(arr,",");
	}
	public static String arrayToString(String[] arr,String splitter) {
		if (arr==null || arr.length==0) {
			return "";
		}
		StringBuilder sb = new StringBuilder();
		for (int i=0;i<arr.length;i++) {
			sb.append(arr[i]);
			if (i<arr.length-1) {
				sb.append(splitter);
			}
		}
		return sb.toString();
	}
	
	/**
	 * 把参数值转换为long型
	 * @param val
	 * @return
	 */
	public static Long getLong(Object val) {
		if (val==null) {
			return null;
		}
		if (val instanceof Long) {
			return (Long)val;
		}
		if (val instanceof Integer) {
			return ((Integer)val).longValue();
		}
		return Long.valueOf(val.toString());
	}
	
	/**
	 * 把参数值转换为Int型
	 * @param val
	 * @return
	 */
	public static Integer getInt(Object val) {
		if (val==null) {
			return null;
		}
		if (val instanceof Long) {
			return ((Long)val).intValue();
		}
		if (val instanceof Integer) {
			return (Integer)val;
		}
		return Integer.valueOf(val.toString());
	}
	public static Float getFloat(Object val){
		if (val==null) {
			return null;
		}
		if (val instanceof Float) {
			return ((Float)val).floatValue();
		}
		if (val instanceof Float) {
			return (Float)val;
		}
		return Float.valueOf(val.toString());
	}
	public static Double getDouble(Object val){
		if (val==null) {
			return null;
		}
		if (val instanceof Double) {
			return ((Double)val).doubleValue();
		}
		if (val instanceof Float) {
			return (Double)val;
		}
		return Double.valueOf(val.toString());
	}
	/**
	 * 生成验证码（0~9，a~z）
	 * @param num 验证码长度
	 * @return 验证码
	 */
	public static String getVerificationCode(int num){
		char[] vc = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
		Random r = new Random();
		if(num<1){
			return null;
		}
		char [] vc_new = new char[num];
		for (int i = 0; i < num; i++) {
			vc_new[i] = vc[r.nextInt(vc.length)];
		}
		return new String(vc_new);
	}
	
}
